﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MT.Common.Helper;
using MT.Common.Helpers;
using MT.Common.Log;
using MT.Common.QueueTask;
using MT.DAL.Abstract.UserCenter;
using MT.Models.Entity;
using MT.Rest.Core.Models;
using MT.Rest.Core.Token;
using MT.WebApi.Core.Auth.OverWrite;
using MT.WebApi.Core.Auth.Policys;
using System;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace MT.Rest.Controllers
{
    /// <summary>
    /// 授权
    /// </summary>
    [Route("api/[controller]")]
    [ApiController, AllowAnonymous, Skip]
    public class SessionController : ControllerBase
    {
        private readonly IUserService _userService;
        //  private readonly PermissionRequirement requirement;
        private readonly IUserLogService _userLogService;
        private readonly IBackgroundTaskQueue _queue;
       
        public SessionController(IUserLogService userLogService, IUserService userService, IBackgroundTaskQueue backgroundTaskQueue
            )
        {
            _userService = userService;
            _userLogService = userLogService;
            _queue = backgroundTaskQueue;
        }


        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("token")]
        public async Task<ActionResult<TokenJwtInfo>> GetJwtStr(LoginRequest request)
        {
            TokenJwtInfo jwtInfo;
            User user;
            if (CellphooneHelper.IsValidCellphone(request.LoginName))
            {
                user = await _userService.GetByPhoneNumber(request.LoginName);
            }
            else
            {
                user = await _userService.GetByUseName(request.LoginName);
            }
            if (user == null)
            {
                return Unauthorized(new { Code = "300151", Msg = "Invalid credentials" });
            }
            if (user.Active == false)
            {
                return BadRequest(new { Code = (int)ErrorCode.UserNotActive, Msg = ErrorCode.UserNotActive.GetEnumDesc() });
            }
            if (user.ExpireTypeDic == "temp" && user.ExpireTime > DateTime.Now)
            {
                return Unauthorized(new { Code = "300151", Msg = "Invalid credentials" });
            }
            if (DateTime.Now > DateTime.Parse("2019-08-31"))
            {
                return BadRequest(new { Code = (int)ErrorCode.InternalError, Msg = "授权已过期" });
            }
            if (PasswordHelper.ValidatePassword(request.Password, user.PasswordSalt, user.PasswordHash))
            {
                var tokenModel = new TokenModelJwt
                {
                    UserId = user.Id,
                    Role = "Client",
                    ExpireTime = request.AutoLogin ? DateTime.Now.AddHours(8) : DateTime.Now.AddMinutes(20),
                    ClientTypeDic = request.ClientTypeDic,
                    Name = user.Name,
                    Phone = user.PhoneNumber,
                };
                jwtInfo = MapperHelper<TokenModelJwt, TokenJwtInfo>.Map(tokenModel);
                jwtInfo.SessionKey = JwtHelper.IssueJwt(tokenModel);
            }
            else
            {
                return BadRequest(new { Code = "300151", Msg = "Invalid credentials" });
            }
            return jwtInfo;
        }

  

        /// <summary>
        /// 请求刷新Token（以旧换新）
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet("refreshToken")]
        public async Task<ActionResult> RefreshToken(string token = "")
        {
            if (string.IsNullOrEmpty(token))
            {
                return Unauthorized(new { Code = "300151", Msg = "Invalid credentials" });
            }
            var tokenModel = JwtHelper.SerializeJwt(token);
            if (tokenModel == null || tokenModel.UserId <= 0)

                return Unauthorized(new { Code = ErrorCode.InternalError, Msg = "认证失败" });
            var user = await _userService.GetUser(tokenModel.UserId);
            if (user == null)
                return Unauthorized(new { Code = ErrorCode.InternalError, Msg = "认证失败" });
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Jti,tokenModel.UserId.ToString()),
                new Claim("Role",tokenModel.Role),
                new Claim("Phone",tokenModel.Phone),
                new Claim("ClientTypeDic",tokenModel.ClientTypeDic),
                new Claim("Name",tokenModel.Name),
                new Claim("UserId",tokenModel.UserId.ToString()),
                new Claim(JwtRegisteredClaimNames.Iat,DateTime.Now.ToString(CultureInfo.InvariantCulture),ClaimValueTypes.Integer64)
            };

            //用户标识
            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            identity.AddClaims(claims);

            var refreshToken = JwtToken.BuildJwtToken(claims.ToArray(), null);
            return new JsonResult(refreshToken);

        }

        /// <summary>
        /// 退出
        /// </summary>
        [HttpPost("out")]
        public async Task OutUser()
        {

        }

    }
}